import React, {Component} from 'react';
import {connect} from 'dva';

import {
		Card, Row, Col,message,
		Form,DatePicker,Select,Button,
		Table,Collapse, Icon
	} from 'antd';
import DefinitionList from '../../../../components/DefinitionList';
import PortSelect from '../../../../components/toolbar/PortSelect';
import BenchSelect from '../../../../components/toolbar/BenchSelect';

const FormItem = Form.Item;
const Option = Select.Option;
const RangePicker = DatePicker.RangePicker;
const Panel = Collapse.Panel;

import style from './home.less'
import {
		Tabtitle,
		IECharts,
		NoData,
		IncomeTrend,
		DataNone,
		NumberWithColor,
		Loading
	} from '../../../../components'

import "../../../../utils/orgchart/jquery.orgchart.js"

import {
  ProlistSelect,
	TimeRangeSelect,
	DateRangePicker,
	IndustrySelect,
	BenchCodeSelect,
	// PdtSelect,
	// BenchCodeSelect2,
} from '../../../../components/ToolbarItem'

/**
 * 工具栏
 * @param {[type]} tag           [所属model]
 * @param {[type]} productList   [产品组合列表]
 * @param {[type]} timeRangeList [时间区间列表]
 * @param {[type]} timeRange     [时间区间值]
//  * @param {[type]} benchCodeList [基准代码列表]
 * @param {[type]} cBenchCode    [基准代码值]
 * @param {[type]} industryList  [行业分类列表]
 * @param {[type]} indunum       [行业分类值]
 * @param {[type]} lPortId       [产品组合id]
 * @param {[type]} beginDate     [开始时间]
 * @param {[type]} endDate       [结束时间]
 * @param {[type]} dispatch      [方法]
 * @param {[type]} location      [路由]
 * @param {[type]} query         [路由query]
 */
const Toolbar=({
		tag,
		productList,
		timeRangeList,
		timeRange,
		cBenchCode,
		industryList,
		indunum,
		lPortId,
		beginDate,
		endDate,
		dispatch,
		ListPdt,
		isShow,
		pdtsearchId,
		BListPdt,
		BisShow,
		BpdtsearchId,
		onePdt,
		location:{
			pathname,
			query
		}
	})=>{
		/**
		 * 查询方法
		 *
		 * 产品组合值为空时，提示'请选择组合'
		 * 时间区间为0时，开始时间和结束时间为空时，提示'请选择时间！'
		 * 符合条件则更改路由
		 */
		const queryData=() => {
			if(!lPortId){
				message.warning('请选择产品组合');
			}else{
				if(timeRange==='0'){
					if(!(beginDate&&endDate)){
						message.warning('请选择时间！');
					}else{
						if(!cBenchCode){
							message.warning('请选择业绩基准！');
						}else{
							dispatch({
								type: `${tag}/changeRouter`,
								query,
								payload:{
									pathname,
									query:{
										lPortId,
										timeRange,
										cBenchCode,
										beginDate,
										endDate,
										indunum
									}
								}
							})
						}

					}
				}else{
					if(!cBenchCode){
						message.warning('请选择业绩基准！');
					}else{
					dispatch({
						type: `${tag}/changeRouter`,
						query,
						payload:{
							pathname,
							query:{
								lPortId,
								timeRange,
								cBenchCode,
								indunum
							}
						}
					})
				}
				}
			}
		}
		return(
			<div className={`toolbar ${style.toolbar}`} style={{position:'relative'}}>

				<Form layout="inline">
					<Row type="flex" justify="start" align="middle">
						<Col>
							<FormItem
								label="组合"
							>
								<ProlistSelect
									data={ListPdt}
									value={lPortId&&ListPdt[0].id!=''?ListPdt.find(item=>item.id==lPortId).value:''}
									dispatch={dispatch}
									tag={tag} />
								{/*<PdtSelect
							  	dispatch={dispatch}
							  	tag={tag}
							  	data={ListPdt}
							  	isShow={isShow}
							  	pdtsearchId={pdtsearchId}
							  	onePdt={onePdt}
							  />*/}
							  {/*<DefinitionList  value={<PortSelect id={lPortId}  location={location} />} />*/}
							</FormItem>
						</Col>
						<Col>
							<FormItem
								label="时间区间"
							>
								<TimeRangeSelect
									data={timeRangeList}
									value={timeRange&&timeRangeList[0].value!=''?timeRangeList.find(item=>item.value==timeRange).name:''}
									dispatch={dispatch}
									tag={tag}/>

							</FormItem>
							{
								timeRange==="0"?<FormItem >
									<DateRangePicker
										beginDate={beginDate}
										endDate={endDate}
										dispatch={dispatch}
										tag={tag}/>
								</FormItem>:null
							}
						</Col>
						<Col>
							<FormItem
								label="行业分类"
							>
								<IndustrySelect
									data={industryList}
									value={indunum&&industryList[0].value!=''?industryList.find(item=>item.value===indunum).name:''}
									dispatch={dispatch}
									tag={tag} />
							</FormItem>
						</Col>
						<Col>
							<FormItem
								label="业绩基准"
							>
								<BenchCodeSelect
									data={BListPdt&&BListPdt.filter(item=>item.id!=lPortId)}
									value={cBenchCode&&BListPdt[0].id!=''?BListPdt.find(item=>item.id==cBenchCode).value:''}
									dispatch={dispatch}
									tag={tag} />
								{/*<BenchCodeSelect2
							  	dispatch={dispatch}
							  	tag='prolist'
							  	data={BListPdt}
							  	BisShow='brinson'
							  	BpdtsearchId={BpdtsearchId}
							  	pdtsearchId={pdtsearchId}
							  	BenchCode ={cBenchCode}
							  />*/}
							</FormItem>
						</Col>
						<Col>
							<Button type="primary" onClick={queryData}>
								查询
							</Button>
						</Col>
					</Row>
				</Form>

			</div>
		)
}
/**
 * 数据统计表
 */
const DataStatistics =(props)=>{
	const {query,dataSource,hostname}=props
	const columns = [
		{
			title: '分类',
			dataIndex: 'indunumname',
			key: 'indunumname',
			width:"8%",
		},
		{
			title: '组合',
			children: [
				{
					title: '组合平均市值权重',
					dataIndex: 'post_weight',
					key: 'post_weight',
					width:"6.2%",
					render: (text, record) => {
						return <em>{text}</em>
					},
				},
				{
					title: '组合平均资金权重',
					dataIndex: 'port_valuepct',
					key: 'port_valuepct',
					width:"6.2%",
					render: (text, record) => {
						return <em>{text}</em>
					},
				},
				{
					title: '组合收益率',
					dataIndex: 'port_rate',
					key: 'port_rate',
					width:"6.2%",
					render: (text, record) => {
						return <NumberWithColor text={text} />
					},
				}, {
					title: '组合收益贡献',
					dataIndex: 'port_contribution',
					key: 'port_contribution',
					width:"6.2%",
					render: (text, record) => {
						return <NumberWithColor text={text} />
					},
				}
			],
		},
		{
			title: '基准',
			children: [
				{
					title: '基准平均权重',
					dataIndex: 'bench_weight',
					key: 'bench_weight',
					width:"6.2%",
					render: (text, record) => {
						return <em>{text}</em>
					},
				}, {
					title: '基准收益率',
					dataIndex: 'bench_rate',
					key: 'bench_rate',
					width:"6.2%",
					render: (text, record) => {
						return <NumberWithColor text={text} />
					},
				}, {
					title: '基准收益贡献',
					dataIndex: 'bench_contribution',
					key: 'bench_contribution',
					width:"6.2%",
					render: (text, record) => {
						return <NumberWithColor text={text} />
					},
				}
			],
		},
		{
			title: '组合与基准的差异',
			children: [
				{
					title: '平均权重差（组合-基准）',
					dataIndex: 'weight_difference',
					key: 'weight_difference',
					width:"8%",
					render: (text, record) => {
						return <em>{text}</em>
					},
				}, {
					title: '超额收益率',
					dataIndex: 'rate_difference',
					key: 'rate_difference',
					width:"6.2%",
					render: (text, record) => {
						return <NumberWithColor text={text} />
					},
				}, {
					title: '超额收益贡献',
					dataIndex: 'contribution_difference',
					key: 'contribution_difference',
					width:"6.2%",
					render: (text, record) => {
						return <NumberWithColor text={text} />
					},
				}
			],
		},
		{
			title: '绩效归因',
			children: [
				{
					title: '资产配置',
					dataIndex: 'allocation_rate',
					key: 'allocation_rate',
					width:"6.2%",
					render: (text, record) => {
						return <NumberWithColor text={text} />
					},
				}, {
					title: '个股选择',
					dataIndex: 'selection_rate',
					key: 'selection_rate',
					width:"6.2%",
					render: (text, record) => {
						return <NumberWithColor text={text} />
					},
				}, {
					title: '交互收益',
					dataIndex: 'interaction_rate',
					key: 'interaction_rate',
					width:"6.2%",
					render: (text, record) => {
						return <NumberWithColor text={text} />
					},
				}, {
					title: '价差收益',
					dataIndex: 'differential_profit',
					key: 'differential_profit',
					width:"6.2%",
					render: (text, record) => {
						return <NumberWithColor text={text} />
					},
				}, {
					title: '残差项',
					dataIndex: 'residual_term',
					key: 'residual_term',
					width:"6.2%",
					render: (text, record) => {
						return <NumberWithColor text={text} />
					},
				}
			],
		},

	]
	let downloadApiQuery=''
	for(let key in query){
		downloadApiQuery+=`&${key}=${query[key]}`
	}
	let downloadUrl=`${hostname==='localhost'?'':'/thfx'}/api/brinsonResult/export?table=brinsonResult`
	return(
				<div className={`table ${style.table}`} style={{marginTop:20}}>
					<Collapse defaultActiveKey={['1']} >
				    <Panel header="数据统计表" key="1">
							<Table
								rowKey='indunum'
								columns={columns}
								{...props}
								pagination={false}
								size="small"
							/>

				    </Panel>

				  </Collapse>
					{
						dataSource&&dataSource.length?<a download={downloadUrl+downloadApiQuery}
							href={downloadUrl+downloadApiQuery}
							style={{position:'absolute',right:'30px',top:'30px',textDecoration: 'none'}}>
							<Icon type="export" /> 导出
						</a>:null
					}

				</div>
	)
}

/**
 * 收益拆分
 */
import TheTree from '../../../../components/TheTree'
const RevenueSplit =({data})=>{
	const myProps={
		width:'100%',
		data:[
			{
			  id:'gpsy',  
			  title:'股票收益',
			  value:data.port_rate,
			  pid:null, 
			},
			{
			  id:'jzsy',  
			  title:'基准收益',
			  value:data.bench_rate,
			  pid:'gpsy', 
			},
			{
			  id:'cesy',  
			  title:'超额收益',
			  value:data.rate_difference,
			  pid:'gpsy', 
			},
			{
			  id:'zcpz',  
			  title:'资产配置',
			  value:data.allocation_rate,
			  pid:'cesy', 
			},
			{
			  id:'ggxz',  
			  title:'个股选择',
			  value:data.selection_rate,
			  pid:'cesy', 
			},
			{
			  id:'jhsy',  
			  title:'交互收益',
			  value:data.interaction_rate,
			  pid:'cesy', 
			}
		]
	}
	return (
		<div className={`chart org`}>
			<TheTree {...myProps} />
		</div>
		
	)
}


/**
 * 绩效归因图表
 * @param {[type]} names  [Y值]
 * @param {[type]} data   [数据]
 * @param {[type]} height [高度]
 * @param {[type]} name   [数据单条名称]
 */
const BrinsonCharts=({names,data,height,name})=>{
  const option = {
    color:['#4fb8ff'],
    tooltip: {
        trigger: 'axis',
        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow',        // 默认为直线，可选为：'line' | 'shadow'
        },
    },
    grid: {
        left: '3%',
        right: '8%',
        bottom: '3%',
        top:"5%",
        containLabel: true,
    },
    xAxis: [
        {
          type: 'value',
        },
    ],
    yAxis: [
        {
      type: 'category',
      axisTick: { show: false },
      data: names,
        },
    ],
    series: [
        {
      name: name,
      type: 'bar',
      barWidth :10,
      itemStyle: {
        normal: {
          color: function (params){
            if(params.data>0){
              return '#c23531'
            }else{
              return  '#749F83'
            }
          }
        }
      },
      label: {
        normal: {
          show: true,
          position: 'right',
        },
      },
      data:data,
        }
    ],
  }
  return (
    <div className={`chart bar ${style.brinsonCharts}`} style={{height:`${height}px`}}>
      <IECharts option={option}/>
    </div>
  )
}

const Brinson = ({dispatch,brinson,prolist,portfolio,brinsonResult,income,location}) =>{

	const {
		lPortId,
		timeRange,
		cBenchCode,
		indunum,
		beginDate,
		endDate,
		pdtsearchId,
		ListPdt,
		isShow,
		onePdt,
		BListPdt
	}=brinson
	// const {lPortId}=portfolio
	// console.log('00000000',portfolio)
	const {
		productList,
		timeRangeList,
		industryList,
		BpdtsearchId,
		BisShow,
	}=prolist
	const {
		names,
		weight,
		rights,
		table,
		org
	}=brinsonResult
	const {
		series
	}=income

	const {pathname,query}=location
	console.log('location>>>211>',location,prolist)
  const tag=pathname.split('/')[pathname.split('/').length-1]
	const toolbarProps={
		tag,
		...prolist,
		...brinson,
		dispatch,
		location,
	}

	let downloadApiQuery=''
	for(let key in query){
		downloadApiQuery+=`&${key}=${query[key]}`
	}
	const hostname=window.location.hostname
	let downloadUrl=`${hostname==='localhost'?'':'/thfx'}/api/brinsonResult/export?`
	let trendDownloadUrl=`${hostname==='localhost'?'':'/thfx'}/api/brinsonResult/exportReturnRate?`

	return (
		<div className={`equity ${style.brinson}`}>
			<Tabtitle value={'Brinson绩效归因'}/>
			<div className="content-inner">
				<Toolbar {...toolbarProps}/>
				{
					(table&&table.length)||(org&&org.indunum)||(series&&series.length)||(weight&&weight.length)||(rights&&rights.length)?(
						<div className="main-content">
							<Card  bordered={false}  className={`module ${style.overview}`}>
								{
									table&&table.length!=1?<DataStatistics dataSource={table} query={query}	hostname={hostname} />:<DataNone />
								}
							</Card>
							<Row>
								<Col span={12}>
									<Card title="收益拆分"
										extra={org&&org.indunum?<a href={downloadUrl+'table=splitReturnRate'+downloadApiQuery} style={{fontWeight:'normal'}}><Icon type="export" /> 导出</a>:null}
										bordered={false}
										className={`module ${style.split}`}
										bodyStyle={{height:280}}>
										{
											org&&org.indunum?<RevenueSplit data={org}/>:<DataNone />
										}
									</Card>
								</Col>
								<Col span={12}>
									<Card title="收益走势"
										extra={series&&series.length&&ListPdt&&ListPdt.length?<a href={trendDownloadUrl+downloadApiQuery} style={{fontWeight:'normal'}}><Icon type="export" /> 导出</a>:null}
										bordered={false}
										
										className={`module ${style.trend}`}>
										<div className="wrap">
											{
												series&&series.length&&ListPdt&&ListPdt.length?
												<IncomeTrend
													data={series}
													benchName={query.cBenchCode?BListPdt.find(item=>item.id==query.cBenchCode).value:''}
													product={query.lPortId?ListPdt.find(item=>item.id==query.lPortId):{id:'',value:''}}
												/>:<DataNone />
											}
										</div>
									</Card>
								</Col>
							</Row>
							<Row>
								<Col span={12}>
									<Card title="组合与业绩基准行业权重差(%)"
										extra={weight&&weight.length?<a href={downloadUrl+'table=weightDifference'+downloadApiQuery} style={{fontWeight:'normal'}}><Icon type="export" /> 导出</a>:null}
										bordered={false}
										
										className={`module ${style.weight}`}>
										{
											weight&&weight.length?<BrinsonCharts data={weight} name="权重差异" names={names} height={(table.length-1)*25} />:<DataNone />
										}
									</Card>
								</Col>
								<Col span={12}>
									<Card title="组合与业绩基准行业超额收益贡献(%)"
										extra={rights&&rights.length?<a href={downloadUrl+'table=excessRate'+downloadApiQuery} style={{fontWeight:'normal'}}><Icon type="export" /> 导出</a>:null}
										bordered={false}
										
										className={`module ${style.rights}`}>
										{
											rights&&rights.length?<BrinsonCharts data={rights} name="超额收益贡献(%)" names={names} height={(table.length-1)*25} />:<DataNone />
										}
									</Card>
								</Col>
							</Row>
						</div>
					):<NoData />
				}
			</div>
		</div>
	)

}

Brinson.propTypes = {
};

export default connect(({brinson,prolist,brinsonResult,income,portfolio}) => ({brinson,prolist,brinsonResult,income,portfolio}))(Brinson);
